<?php

/**
 * Class descript.
 * User: chan
 * Date: 2017/8/16 19:35
 */
namespace WeChat;
use think\Cache;

class AccessToken
{
    const API_TOKEN = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
    protected $appid;
    protected $secret;
    public $access_token ='';
    /**
     * Constructor.
     * @param $appId string
     * @param $secret string
     */
    public function __construct($options)
    {
        $this->appid = $options['app_id'];
        $this->secret = $options['secret'];
        //缓存失效，重新获取access token
        if(Cache::get('access_token')){
            $this->access_token = Cache::get('access_token');
        }else{
            $this->getAccessToken();
        }
    }
    public function getAccessToken()
    {
        $data = httpRequest(sprintf(self::API_TOKEN,$this->appid,$this->secret));
        $data = json_decode($data,true);
        Cache::set('access_token',$data['access_token'],7200);
    }
}